package com.tgy.blog.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.tgy.constant.RedisKey;
import com.tgy.util.RedisUtils;
import com.tgy.util.RestTemplateUtil;
import com.tgy.vo.GitCommitHistoryVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/8/3 17:10
 */
//1.主要用于标记配置类，兼备Component的效果。
@Configuration
// 2.开启定时任务
@EnableScheduling
public class ScheduleTask {

    @Resource
    private RedisUtils redis;
    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Value("${tgy.gitAccessToken}")
    private String accessToken;
    @Value("${tgy.owner}")
    private String owner;
    @Value("${tgy.repo}")
    private String repo;


    /**
     * 从git获取提交记录
     * 每天凌晨1点执行
     */
    //3.添加定时任务
    @Scheduled(cron = "0 0 1 1/1 * ?")
    public void getGitCommitHistory() {

        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+08:00'");

        // 从缓存获取
        String commitHistory = redis.get(RedisKey.GIT_COMMIT_HISTORY);
        List<GitCommitHistoryVo> list = new ArrayList<>();
        String since = "1998-01-29T00:00:00+08:00";
        // 控制第一条数据是否排除
        boolean isHistory = false;
        // 控制循环
        boolean isWhile = true;
        if (StrUtil.isNotBlank(commitHistory)){
            list = JSONObject.parseArray(commitHistory, GitCommitHistoryVo.class);
            GitCommitHistoryVo gitCommitHistoryVo = list.get(0);
            String date = gitCommitHistoryVo.getDate();
            since = date.replace(" ","T")+"+08:00";
            isHistory = true;
            isWhile = false;
        }
        // 获取当前ISO 8601格式的时间
        String until = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx").format(ZonedDateTime.now());

        // 请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        int i = 1;
        do {
            Map<String,String> param = new HashMap<>();
            String s = restTemplateUtil.GetData("https://gitee.com/api/v5/repos/"
                    +owner+"/"+repo+"/commits?access_token="+accessToken+"&since="+since+"&until="+until+"" +
                    "&page="+i+"&per_page=100", param);

            List lists = JSONObject.parseObject(s, List.class);

            if (isHistory && lists.size()>0){
                lists.remove(0);
            }
            for (Object o : lists) {
                HashMap hashMap = JSONObject.parseObject(o.toString(), HashMap.class);
                Object commit = hashMap.get("commit");
                HashMap hashMap1 = JSONObject.parseObject(commit.toString(), HashMap.class);
                Object message = hashMap1.get("message");
                Object author2 = hashMap1.get("author");
                HashMap hashMap3 = JSONObject.parseObject(author2.toString(), HashMap.class);
                Object name = hashMap3.get("name");
                String date = hashMap3.get("date").toString();
                date = date.replace("T"," ").replace("+08:00","");
                // Date date = sdf.parse(isoDate);

                Object email = hashMap3.get("email");


                Object author = hashMap.get("author");
                HashMap hashMap2 = JSONObject.parseObject(author.toString(), HashMap.class);
                Object authorName = hashMap2.get("name");

                GitCommitHistoryVo vo = new GitCommitHistoryVo(name.toString(),date,email.toString(),message.toString(),authorName.toString());
                list.add(vo);
            }
            i ++;
            if (CollectionUtil.isEmpty(lists)){
                isWhile = false;
            }
        }while (isWhile);



        list = list.stream().sorted((o1, o2) -> o2.getDate().compareTo(o1.getDate())).collect(Collectors.toList());
        redis.set(RedisKey.GIT_COMMIT_HISTORY,JSONObject.toJSONString(list));

        System.err.println("执行 拉取Git记录 静态定时任务时间: " + LocalDateTime.now());
    }

    /**
     * 每天凌晨过5秒 清除每日访问次数限制
     */
    @Scheduled(cron = "5 0 0 1/1 * ?")
    public void clearCommentFileNumber(){
        Set<String> keys = redis.keys(RedisKey.COMMENT_FILE_NUMBER +":*");
        for (String key : keys) {
            redis.del(key);
        }
        System.err.println("执行 清除每日访问次数 静态定时任务时间: " + LocalDateTime.now());
    }

}
